import { useState, useEffect } from 'react';
import Taro, { FC, useRouter } from '@tarojs/taro';
import { Subject, Subscription } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';
import { View, Text, Image, CheckboxGroup, Label, Checkbox, } from '@tarojs/components'

import { AtForm, AtSwitch, AtList, AtListItem, AtInput, AtIcon, AtCheckbox } from 'taro-ui'
import "taro-ui/dist/style/components/switch.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/checkbox.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/button.scss" // 按需引入 

import { SignInSettingReq } from '@/models/request/roomReq';
import { getLogger } from '@/utils/log';

import './index.scss'
import { useRoomFacade } from './useRoomFacade';

//签到设置
export const SignInSetting: FC = () => {
  const logger = getLogger("/pages/liveRoom/signInSetting");

  const [roomFacade, forceSignIn] = useRoomFacade()

  const router = useRouter();
  const roomId = router.params.roomId || '';

  //是否开启签到
  const [hasSignIn, setHasSignIn] = useState(false)
  //是否强制签到
  const [forceSign, setForceSign] = useState(forceSignIn);
  const [liveType, setLiveType] = useState(Number(router.params.liveType)) //直播类型
  const handleHasSignIn = (value: boolean) => {
    setHasSignIn(value)
  }

  const handleForceSign = (value: boolean) => {
    setForceSign(value)
  }

  // 初始化按钮接收参数subject，所有按钮或者操作都可以通过这个emmiter触发
  const initSubject = () => new Subject<any>();
  const [emitter, setEmitter] = useState<Subject<any>>(initSubject)

  // 必选项的操作
  const [select, setSelect]: any = useState([])
  const checkboxOption = [{
    value: 'true',
    label: '必选项',
  }]
  const selectOption: any = []
  //点击勾选触发
  const handleChange4 = (index, value) => {
    value.includes('true') ? diyContent[index].required = true : diyContent[index].required = false
    diyContent.map(item => {
      selectOption.push([item.required.toString()])
    })
    setSelect(selectOption)
    console.log(value, '点击必选项', index, '选项', selectOption[index], selectOption);
  }

  //签到数据
  const [signInOption, setSignInOption] = useState([
    {
      property: 'name',
      title: '姓名',
      required: false,
    }, {
      property: 'company',
      title: '机构名称',
      required: false,
    },
    {
      property: 'position',
      title: '职务',
      required: false,
    }, {
      property: 'phone',
      title: '电话号码',
      required: false,
    }, {
      property: 'idNum',
      title: '身份证号',
      required: false,
    }])
  // 自定义数据
  const [diyContent, setDiyContent] = useState([
    {
      property: 'property0',
      title: '',
      required: false,
    }

  ])

  //更改复选框的状态
  const checkboxChange = (e) => {
    console.log('复选框发生点击事件，传的值为', e.detail);
    //若没选择， 清空复选框
    signInOption.map(i => { if (e.detail.value.indexOf(i.title) === -1) { i.required = false } })
    // 勾选已选择的选项
    e.detail.value.map(item => {
      signInOption.map(i => {
        if (item === i.title) {
          i.required = true
        }
      })
    })
    //react监听不到深层数据修改，采用深拷贝方式
    setSignInOption(JSON.parse(JSON.stringify(signInOption)))
  }

  // 强制签到说明
  const showTip = () => {
    Taro.showToast({
      icon: 'none',
      title: '开启后，观众需签到后才可观看直播'
    })
  }

  // 输入自定义签到内容
  const handleChangeDIY = (value, e) => {
    // console.log('这是我输入的内容', value, e, diyContent)
    // // 需要获取内容对应的序号
    // const index = e.mpEvent.target.id
    // console.log(index, '是我要的序号id吗', value)
  }
  //  更新自定义签到内容
  const handleBlurDIY = (value, e) => {
    // 需要获取内容对应的序号
    const index = e.mpEvent.target.id
    diyContent[index].title = value;
    setDiyContent(JSON.parse(JSON.stringify(diyContent)))
    console.log('自定义的内容', diyContent);

  }

  // 删除内容 每次点击，删除最后一个
  const handledelDiy = (index) => {
    // if (diyContent.length <= 1) {
    //   return false
    // }
    diyContent.splice(index, 1);
    setDiyContent(JSON.parse(JSON.stringify(diyContent)))
    console.log('自定义的内容', diyContent);

  }

  // 添加内容
  const addContent = () => {
    if (diyContent.length < 5) {
      // if (select.includes('true')) {
      diyContent.push({
        property: `property${diyContent.length}`,
        title: '',
        required: select.includes('true') ? true : false,
        // required: true,
        //   })
        // } else {
        //   diyContent.push({
        //     property: `property${diyContent.length}`,
        //     title: '',
        //     required: false,
      })
    }
    console.log(diyContent, select);
    setDiyContent(JSON.parse(JSON.stringify(diyContent)))
  }


  // 保存设置
  const saveSetting = () => {

    //需要分别对固定内容和自定义内容筛选做处理， 如果固定内容required为false不传，自定义内容title === '' 也不传
    const newSignIn = signInOption.filter(item => { return item.required === true })
    const newDiyContent = diyContent.filter((item, index) => {
      item.property = 'property' + index
      return item.title.trim() !== ''
    })
    console.log(newDiyContent, 'ddd');

    const paramObj = { hasSignIn, forceSign, signInOptions: [...newSignIn, ...newDiyContent] } as SignInSettingReq;
    console.log('点击触发', paramObj);
    emitter.next(paramObj);
  }
  //提交设置时确定
  useEffect(() => {
    const subscriptions: Subscription[] = [
      emitter.asObservable()
        .pipe(
          switchMap(paramObj => {
            if (paramObj.hasSignIn) {
              if (paramObj.signInOptions.length === 0) {
                throw Taro.showToast({
                  icon: 'none',
                  title: '请填写签到内容',
                  duration: 2000
                })
              }
            }
            return roomFacade.signInSetting(roomId, paramObj as SignInSettingReq)
          })
        )
        .subscribe(
          () => {
            Taro.showToast({
              icon: 'none',
              title: '保存成功',
              duration: 2000
            })

            setTimeout(() => {
              if (liveType === 0) {
                Taro.navigateTo({
                  url: `/pages/liveRoom/graphicLive/index?roomId=${roomId}`
                })
              } else {
                Taro.navigateTo({
                  url: `/pages/liveRoom/room/index?roomId=${roomId}`
                })
              }
            }, 1000)
          },
          () => {
            //异常时恢复emitter以便可以重新触发点击
            setEmitter(initSubject);
          }
        ),
    ]

    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [emitter])

  // 获取设置
  useEffect(() => {
    const subscriptions: Subscription[] = [
      roomFacade.getSignInFrom()
        .pipe(
          filter(res => res && res.length > 0)
        )
        .subscribe(
          (res) => {
            setHasSignIn(true);

            // 返回值是一个数组，将数组进行处理
            console.log(res, '获取到的数据');
            //处理数据，分别处理固定内容和自定义内容
            res.map(item => {
              signInOption.map(i => {
                if (item.property === i.property) {
                  i.required = item.required
                }
              })
              if (item.property.includes('property')) {
                if (diyContent[0].title === '') {
                  diyContent.splice(0, 1, item)
                } else {
                  diyContent.push(item)
                }
              }
            })
            diyContent.map(item => {
              selectOption.push([item.required.toString()])
            })
            setSelect(selectOption)
            setSignInOption(JSON.parse(JSON.stringify(signInOption)))
            setDiyContent(JSON.parse(JSON.stringify(diyContent)))
          },
          logger.ERROR
        )
    ]
    return () => { subscriptions.map(sub => sub.unsubscribe()) };
  }, [])

  return (
    <View className='index'>
      <View className='main'>
        {/* 签到启用 */}
        <View className='diy-item'>
          <View className='diy-item-left'><Text>签到启用</Text></View>
          <View className='diy-item-right'>
            <AtForm>
              <AtSwitch checked={hasSignIn} onChange={handleHasSignIn} color={MAIN_COLOR} />
            </AtForm>
          </View>
        </View>

        {/* 强制签到 */}
        {hasSignIn && (
          <View>
            <View className='diy-item' style='border:none'>
              <View className='diy-item-left'>
                <Text>强制签到</Text>
                <View className='mark' onClick={showTip}>
                  <Image src={ASSETS_PATH + '/question.png'} className='mark-img'></Image>
                </View>
              </View>
              <View className='diy-item-right'>
                <AtForm>
                  <AtSwitch checked={forceSignIn} onChange={handleForceSign} color={MAIN_COLOR} />
                </AtForm>
              </View>
            </View>
            {/* 签到内容 */}
            <View>
              <AtList>
                <AtListItem className='text' title='签到内容' extraText='（至少一个以上）' />
              </AtList>
              <CheckboxGroup className='checkbox-group' onChange={checkboxChange}>
                {signInOption.map((item, index) => {
                  return (
                    <Label key={String(index)} className={signInOption[index].required ? 'checkbox checked' : 'checkbox'}>
                      <Checkbox value={item.title} checked={item.required} className='check-item' />
                      {item.title}
                    </Label>
                  )
                })}
              </CheckboxGroup>
            </View>
            {/* 自定义签到内容 */}
            <View>
              <AtList>
                <AtListItem className='text' title='自定义签到内容' />
              </AtList>
              {diyContent.map((item, index) => {
                return (
                  <View key={String(index)} className='input-box'>
                    <AtForm>
                      <AtInput
                        name={index + ''}
                        type='text'
                        placeholder='请输入签到内容'
                        value={item.title}
                        onChange={handleChangeDIY.bind(this)}
                        onBlur={handleBlurDIY.bind(this)}
                        className='input-content'
                      />
                    </AtForm>
                    <View className='border'>
                      <View className='left' onClick={handledelDiy.bind(this, index)}>
                        <AtIcon value='trash' size='25' color='#333333'></AtIcon><Text className='del'>删除</Text>
                      </View>
                      <View className='right'>
                        <AtCheckbox
                          options={checkboxOption}
                          selectedList={select[index]}
                          onChange={handleChange4.bind(this, index)}
                        />
                      </View>
                    </View>
                  </View>
                )
              })
              }
              <View className='add-content' onClick={addContent}>
                <Text>添加内容({diyContent.length}/5)</Text>
              </View>
            </View>
          </View>
        )}
        <View className='button' onClick={saveSetting}>
          <Text className='save'>保存</Text>
        </View>

      </View>
    </View >
  )
}
export default SignInSetting
